package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"strconv"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
)

type CollegeScore struct {
	Ctx iris.Context
}

//补充高考分数
func (c *CollegeScore) PostScore() interface{} {
	channel := c.Ctx.PostValue("channel")
	score := c.Ctx.PostValue("score")
	userType := c.Ctx.PostValue("userType")

	if channel == "" || score == "" || userType == "" {
		return utils.CommonRes(1000, fmt.Sprintf("参数有误"), "")
	}

	var userId int64
	if channel == "wechat" {
		token := c.Ctx.GetHeader("token")
		if token == "" {
			return utils.CommonRes(1000, fmt.Sprintf("token为空"), "")
		}

		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错"), "")
		}

		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%s userId", channel))
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("连接数据库出错: %s", err), "")
	}

	testScore,err := strconv.Atoi(score)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据类型转换出错: %s", err), "")
	}

	userInfo := new(models.User)
	userInfo.TestScore = testScore

	_, err = db.Where("user_id = ?", userId).InsertOne(userInfo)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("插入数据出错"), "")
	}

	return utils.CommonRes(20000, fmt.Sprintf("补充高考成绩成功"), "")
}
